define(["jquery", "easy-admin"], function ($, ea) {

    var init = {
        table_elem: '#currentTable',
        table_render_id: 'currentTableRenderId',
        index_url: 'benefit.calculate/index',
        upload_url: 'benefit.calculate/upload',
        calculate_url: 'benefit.calculate/calculate',
        detail_url: 'benefit.calculate/detail',
        empty_url: 'benefit.calculate/empty',
    };

    return {

        index: function () {
            ea.table.render({
                init: init,
                toolbar: [
                    [{
                        text: '上传Excel',
                        url: init.upload_url,
                        method: 'open',
                        auth: 'upload',
                        class: 'layui-btn layui-btn-sm layui-btn-success ',
                        icon: 'fa fa-cloud-upload',
                        extend: 'data-width="50%" data-height="70%"'
                    },
                    {
                        text: '计算效益',
                        url: init.calculate_url,
                        method: 'open',
                        auth: 'calculate',
                        class: 'layui-btn layui-btn-sm layui-btn-success ',
                        icon: 'fa fa-cloud-upload',
                        extend: 'data-full="true"',
                    },
                    {
                        text: '清空',
                        url: init.empty_url,
                        method: 'request',
                        auth: 'calculate',
                        class: 'layui-btn layui-btn-sm layui-btn-danger ',
                        icon: 'fa fa-cloud-upload',
                        extend: 'data-width="50%" data-height="42%"'
                    }],
                    'refresh'],
                cols: [[
                    { type: 'checkbox' },
                    { field: 'id', title: 'id', search: false, width: 80 },
                    { field: 'well_number', title: '井号' },
                    { field: 'management_unit', title: '管理区', search: false },
                    { field: 'oilgas_unit', title: '油气田', search: false },
                    { field: 'measures_after_date', title: '开井日期', search: false },
                    { field: 'before_capacity', title: '措施前产量', search: false },
                    { field: 'after_capacity', title: '措施后产量', search: false },
                    { field: 'calculate_days', title: '天数', search: 'select', selectList: { '< 50': '<30天', '> 30': '>30天' }, searchOp: '>', width: 80 },
                    { field: 'normal_labor_cost', title: '劳务费', search: false },
                    { field: 'material_cost', title: '主材费', search: false },
                    { field: 'self_labor_cost', title: '自营修复', search: false },
                    { field: 'other_labor_cost', title: '外部修复', search: false },
                    { field: 'benefit', title: '效益', search: false },
                    {
                        field: 'result', title: '结果', search: false, search: 'select', selectList: { '1': '有效', '0': '无效' }, templet: function (d) {
                            if (d.result === 1) {
                                return ' <button type="button" class="layui-btn layui-btn-sm">有效</button>'
                            } else {
                                return ' <button type="button" class="layui-btn layui-bg-red layui-btn-sm">无效</button>'
                            }
                        }
                    },
                    { field: 'file', title: '文件' },
                    {
                        width: 150,
                        title: '操作',
                        templet: ea.table.tool,
                        operat: [
                            [{
                                text: '详情',
                                url: init.detail_url,
                                method: 'open',
                                auth: 'detail',
                                class: 'layui-btn layui-btn-xs layui-btn-success',
                                extend: 'data-full="true"',
                            }]]
                    }
                ]],
            });

            ea.listen();
        },
        upload: function () {
            layui.use(['upload', 'laydate'], function () {
                var upload = layui.upload;
                var $ = layui.$;
                var laydate = layui.laydate;
                var loadingIndex = 0;
                // 日期范围
                laydate.render({
                    elem: '#calculate-range',
                    range: ['#start-date', '#end-date'],
                    rangeLinked: true,
                    done: function (value, startDate, endDate) {
                    }
                });

                //上传
                upload.render({
                    elem: '#upload-excel',
                    url: 'upload',
                    auto: false,
                    accept: 'file',
                    bindAction: '#upload-action',
                    data: {
                        start: function () {
                            return $("#start-date").val();
                        },
                        end: function () {
                            return $("#end-date").val();
                        }
                    },
                    before: function () {
                        loadingIndex = layer.msg('上传中', {
                            icon: 16,
                            shade: 0.5,
                            time: 10000
                        });
                    },
                    done: function (res) {
                        if (res.code == 0) {
                            layer.msg(res.msg, { icon: 2 })
                        } else {
                            layer.close(loadingIndex);
                            var index = parent.layer.getFrameIndex(window.name);
                            parent.layer.msg(res.msg, { icon: 1 })
                            parent.layer.close(index);
                        }
                    }
                });

            })

            ea.listen();
        },
        calculate: function () {
            var options = init;
            var filter = { 'file': $("#file").val() };
            var op = { 'file': "=" };
            var loadingIndex = 0;
            options['index_url'] = options['index_url'] + '?filter=' + JSON.stringify(filter) + '&op=' + JSON.stringify(op);
            let _table = ea.table.render({
                init: options,
                toolbar: ['refresh'],
                cols: [[
                    { type: 'checkbox' },
                    { field: 'id', title: 'id', search: false, width: 80 },
                    { field: 'well_number', title: '井号' },
                    { field: 'management_unit', title: '管理区', search: false },
                    { field: 'oilgas_unit', title: '油气田', search: false },
                    { field: 'measures_after_date', title: '开井日期', search: false },
                    { field: 'before_capacity', title: '措施前产量', search: false },
                    { field: 'after_capacity', title: '措施后产量', search: false },
                    { field: 'calculate_days', title: '天数', search: 'select', selectList: { '< 50': '<30天', '> 30': '>30天' }, searchOp: '>', width: 80 },
                    { field: 'normal_labor_cost', title: '劳务费', search: false },
                    { field: 'material_cost', title: '主材费', search: false },
                    { field: 'self_labor_cost', title: '自营修复', search: false },
                    { field: 'other_labor_cost', title: '外部修复', search: false },
                    { field: 'benefit', title: '效益', search: false },
                    {
                        field: 'result', title: '结果', search: false, search: 'select', selectList: { '1': '有效', '0': '无效' }, templet: function (d) {
                            if (d.result === 1) {
                                return ' <button type="button" class="layui-btn layui-btn-sm">有效</button>'
                            } else {
                                return ' <button type="button" class="layui-btn layui-bg-red layui-btn-sm">无效</button>'
                            }
                        }
                    }
                ]],
            });

            layui.use(['upload', 'laydate', 'form', 'table'], function () {
                var laydate = layui.laydate;
                var form = layui.form;
                var table = layui.table;
                // 日期范围
                laydate.render({
                    elem: '#end_date',
                    format: 'yyyy-MM-dd',
                    value: today()
                });
                //lay-submit="benefit.calculate/calculate"
                form.on('submit(submit)', function (data) {
                    var field = data.field; // 获取表单全部字段值

                    var confirm_index = layer.confirm('计算需要一定的时间，请您耐心等待', {
                        btn: ['确定', '关闭'] //按钮
                    }, function () {
                        loadingIndex = layer.msg('计算中，请稍后...', {
                            icon: 16,
                            shade: 0.5,
                            time: 10000
                        });
                        $.ajax({
                            url: '/admin/benefit.calculate/calculate',
                            data: field,
                            type: 'post',
                            success: function (res) {
                                layer.close(loadingIndex);
                                layer.msg(res.msg, { icon: 1 })
                                _table.reload()
                            },
                            error: function (res) {
                                layer.msg(res.msg, { icon: 2 })
                                _table.reload()
                            },
                        })
                    }, function () {
                        layer.close(confirm_index);
                    });
                    return false; // 阻止默认 form 跳转
                });
            })

            function today() {
                // 1. 获取当前日期
                var today = new Date();

                // 2. 格式化日期为 yyyy-MM-dd（与 laydate 的 format 对应）
                var year = today.getFullYear(); // 年（4位）
                var month = String(today.getMonth() + 1).padStart(2, '0'); // 月（补零，01-12）
                var day = String(today.getDate()).padStart(2, '0'); // 日（补零，01-31）
                var todayStr = `${year}-${month}-${day}`; // 结果：2025-10-20（示例）
                return todayStr
            }
            ea.listen();
        },
        empty: function () {
            ea.listen();
        },
    };
});